const gulp = require('gulp');
const rename = require('gulp-rename');
const uglify = require('gulp-uglify');
const encrypt = require('gulp-js-encrypt');
const connect = require('gulp-connect');
// css
const autoprefixer = require('gulp-autoprefixer');
const cleanCss = require('gulp-clean-css');
const sass = require('gulp-sass')(require('sass'));
// script
const rollup = require('gulp-better-rollup');
const buble = require('@rollup/plugin-buble');
const json = require('@rollup/plugin-json');

function livereload(cb) {
  connect.server({
    root      : 'app',
    port      : 3088,
    livereload: true,
    fallback  : 'app/views/error/404.html'
  });

  cb && cb();
}

function _buble() {
  return gulp.src('./src/es/index.js')
    .pipe(rollup({
      external: ['layui', 'top.layui'],
      plugins : [
        json(),
        buble()
      ]
    }, {
      name   : 'admin',
      format : 'iife',
      file   : 'admin.js',
      globals: {
        layui      : 'layui',
        'top.layui': 'top.layui'
      }
    }))
    .pipe(gulp.dest('./app/js/core'))
    .pipe(connect.reload());
}

function script() {
  return gulp.src('./app/js/core/@(admin|view).js')
    .pipe(uglify())
    .pipe(encrypt())
    .pipe(rename({ suffix: '.min' }))
    .pipe(gulp.dest('./app/js/core'));
}

function style() {
  return gulp.src('./src/scss/index.scss')
    // nested, expanded, compact, compressed
    .pipe(sass({ outputStyle: 'expanded' }).on('error', sass.logError))
    .pipe(autoprefixer({ cascade: false }))
    .pipe(rename('admin.css'))
    .pipe(gulp.dest('./app/css'))
    .pipe(cleanCss({ compatibility: 'ie9' }))
    .pipe(rename('admin.min.css'))
    .pipe(gulp.dest('./app/css'))
    .pipe(connect.reload());
}

exports.preview = livereload;
exports.script = gulp.series(_buble, script);
exports.style = style;
exports.build = gulp.parallel(gulp.series(_buble, script), style);

function watch(cb) {
  gulp.watch(['./src/scss/**/*'], style);
  gulp.watch(['./src/es/**/*'], gulp.series(_buble, script));
  cb();
}

exports.default = gulp.parallel(livereload, watch);
